<?php

namespace App\Admin\Controllers;

use App\Models\Base\LogEmail;
use App\Models\Base\ServerList;
use App\Service\PlayerService;
use App\Service\ServerService;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\Input;

/**
 *邮件奖励.
 */
class MailRewardController extends Controller
{
    use ModelForm;

    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.gm_tool'));
            $content->description(trans('game.email'));
            $content->body($this->grid());
        });
    }

    protected function grid()
    {
        //忽略serverList Model软删除
        ServerList::$soft = true;
        $grid = Admin::grid(LogEmail::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->id('ID')->sortable();
            $grid->title(trans('game.title'));

            $grid->serverName()->name(trans('game.server_name'))->display(function ($name){
                return $name ?? trans('game.server_all');
            });
            $grid->recipient_type(trans('game.type'))->display(function ($type) {
                return $type ? trans('game.all_people') : trans('game.specified');
            });
            $grid->recipients(trans('game.recipient'))->display(function ($recipients) {
                return str_limit($recipients, 15, '...');
            });
            $grid->content(trans('game.content'))->display(function ($content) {
                return str_limit($content, 15, '...');
            });
            $grid->column(trans('game.item'))->expand(function () {
                $headers = ['ID', trans('game.item_name'), trans('game.status'), trans('game.number')];
                $rows = [];
                if ($this->emailItem) {
                    foreach ($this->emailItem as $key => $value) {
                        $item = $value->getItems;
                        if (!$item) {
                            continue;
                        }
                        $status = $value->flag ? trans('game.bind') : trans('game.not_bind');
                        $row = [$item->item_no, $item->name, $status, $value->num];
                        $rows[] = $row;
                    }
                }

                return new Table($headers, $rows);
            }, trans('game.an'));
            $grid->status(trans('game.status'))->display(function ($status) {
                return $status ? trans('game.complete') : trans('game.sent');
            });
            $grid->send_at(trans('game.send_time'))->display(function ($send_at) {
                return $send_at ? $send_at : trans('game.send_in_time');
            });
            $grid->admin_name(trans('game.sender'));
            $grid->created_at(trans('game.operating_time'));
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->equal('server_id', trans('game.server_name'))->select(ServerList::all()->pluck('name', 'server_id'));
                $filter->like('title', trans('game.title'));
                $filter->like('recipients', trans('game.recipient'));
            });
            $grid->disableActions();
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });
        });

        return $grid;
    }

    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.gm_tool'));
            $content->description(trans('admin.new'));
            $content->body($this->form());
        });
    }

    protected function form()
    {
        return Admin::form(LogEmail::class, function (Form $form) {
            $form->select('server_id', trans('game.server_name'))->options(ServerService::getServerList())->rules('required|numeric');
            $form->radio('recipient_type', trans('game.type'))->options([trans('game.specified'), trans('game.all_people')])->default(1);
            $form->text('level_section', trans('game.level_interval'))->attribute(['id' => 'level_section'])->help(trans('game.format').'xx-xx');

            $form->multipleSelect('recipients', trans('game.recipient'))->attribute(['id' => 'recipients'])->ajaxLoad('server_id', route('api.player'));
            $form->text('title', trans('game.title'))->rules('required|max:24');
            $form->textarea('content', trans('game.content'))->rows(3)->rules('required|max:160')->help(trans('game.content_desc'));

            $form->hasMany('emailItem', trans('game.item_select'), function (Form\NestedForm $form) {
                $form->select('item_id', trans('game.item_name'))->ajax(route('api.getItem'))->help(trans('game.keywords'));
                $form->text('num', trans('game.count'))->rules('required|max:999');
                $form->radio('flag', trans('game.type'))->options([trans('game.not_bind'), trans('game.bind')])->default(1);
            });
            $form->datetime('send_at', '发送时间')->help(trans('game.null_is_send_in_time'));
            $this->roleScript();

            $form->saving(function ($form) {
                $admin_name = \Auth::guard('admin')->user()->name;
                $form->model()->admin_name = $admin_name;
                $post = Input::post();
                if (!$post['send_at']) {
                    //发送给游戏服
                    $form->model()->status = 1;
                    $num = $this->sendMail();
                } else {
                    $num = true;
                }
                if (!$num) {
                    return back()->withInput(admin_toastr(trans('game.gs_communication_failed'), 'error'));
                }
            });
        });
    }

    /**
     * [sendMail 发送邮件给游戏服].
     *
     * @Author   王文凡
     * @DateTime 2018-04-13
     *
     * @version  1.0
     *
     * @return int
     */
    protected function sendMail()
    {
        $post = Input::post();
        if ($post['send_at']) {
            return true;
        }
        $emailItem = $post['emailItem'] ?? [];

        return PlayerService::sendGameMail($post, $emailItem);
    }
}
